package sebjul.ecom.servlet;

import java.io.*;
import java.util.*;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sebjul.ecom.dao.*;
import sebjul.ecom.entities.*;


@WebServlet("/ModifGenre")
public class ModifGenre extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	GenreDao genreDao;
	
	@EJB
	ArticleDao articleDao;
	
    public ModifGenre() {
        super();
        // TODO Auto-generated constructor stub
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String act = request.getParameter("act");
    	if (act != null && act.equals("del")) {
    		int id = Integer.parseInt(request.getParameter("id"));
    		Genre genre = genreDao.findGenreById(id);
//    		Genre genre = genreDao.findGenreByIdJoin(id);
//    		for (Article a : genre.getArticles()) {
//    			a.removeGenre(genre);
//    			articleDao.updateArticle(a);
//    		}
    		genreDao.deleteGenre(genre);
    	}
    	try {Thread.sleep(500);} catch (Exception e) {} // Latence pour suppression effective du genre
    	RequestDispatcher rd = request.getRequestDispatcher("ListGenres");
    	rd.forward(request, response);		
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("submit").equals("Annuler"))	{
			RequestDispatcher rd = request.getRequestDispatcher("ListGenres");
			rd.forward(request, response);
		} else {
			List<Genre> genres = genreDao.findGenres();
			for (Genre g : genres) {
				try {
					String gStr = request.getParameter("genreId"+g.getId());
					g.setGenre(gStr);
					genreDao.updateGenre(g);
					List<Genre> genresDB = genreDao.findGenres();
					ServletContext servletContext = request.getServletContext();
					servletContext.setAttribute("genres", genresDB);
				} catch (Exception e) {}
			}
			RequestDispatcher rd = request.getRequestDispatcher("acceuil");
			rd.forward(request, response);
		}
	}
}
